<!DOCTYPE html>
<html lang="zh">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
	</head>
	<body>
		<video src="" id="vd" style="width: 200px;height: 350px" autoplay></video>
		<script type="text/javascript" charset="utf-8">
			function getQueryVariable(variable) {
				var query = window.location.search.substring(1);
				var vars = query.split("&");
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split("=");
					if (pair[0] == variable) {
						return pair[1];
					}
				}
				return "";
			};

			async function subStream() {
				const id = getQueryVariable("id")
				const name = getQueryVariable("name")
				const audio = true
				const video = true
				const roomId = "videocall"
					const pc = new RTCPeerConnection(null);
				pc.addTransceiver('audio', {
					direction: 'recvonly'
				});
				pc.addTransceiver('video', {
					direction: 'recvonly'
				});
				let offer = await pc.createOffer();
				let stream = new MediaStream();
				pc.ontrack = function(event) {
					console.log(event);
					stream.addTrack(event.track);
				};
				await pc.setLocalDescription(offer);
				let session = await new Promise(function(resolve, reject) {
					// @see https://github.com/rtcdn/rtcdn-draft
					let data = {
						api: `${config.srsUrl}/rtc/v1/play/`,
						tid: id,
						streamurl: `webrtc://${config.srsUrl.replaceAll('https://', '')
          .replaceAll('http://', '')}/${roomId}/${id}`,
						clientip: null,
						sdp: offer.sdp,
					};
					console.log('Generated offer: ', data);

					const xhr = new XMLHttpRequest();
					xhr.onload = function() {
						if (xhr.readyState !== xhr.DONE) return;
						if (xhr.status !== 200) return reject(xhr);
						const data = JSON.parse(xhr.responseText);
						console.log('Got answer: ', data);
						return data.code ? reject(xhr) : resolve(data);
					};
					xhr.open('POST', `${config.srsUrl}/rtc/v1/play/`, true);
					xhr.setRequestHeader('Content-type', 'application/json');
					xhr.send(JSON.stringify(data));
				});
				await pc.setRemoteDescription(
					new RTCSessionDescription({
						type: 'answer',
						sdp: session.sdp
					}),
				);

				function close() {
					stream.getTracks().forEach(function(track) {
						track.stop();
						stream.removeTrack(track);
					});
					pc.close();
				}

				return {
					id,
					roomId,
					pc,
					stream,
					name,
					audio: audio ?? false,
					video: video ?? false,
					close,
				};
			}
			
			subStream().then(res=>{
				console.log(res)
				document.getElementById("vd").srcObject = res.stream
				setTimeout()
			})
		</script>
	</body>
</html>